<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button @click="rulesAdd">添加角色</el-button>
      <el-table border :data="rolesList" highlight-current-row row-class-name style="width: 100%">
        <el-table-column type="expand" label="序号" width="50">
          <template slot-scope="scope">
            <el-row :class="['bdTopBorder', i1 === 0 ? 'bdTopBorder' : '', 'vcenter']" :gutter="20" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <el-col :span="6"
                ><el-tag closable @close="removeRoles(scope.row, item1.id)">{{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>

              <el-col :span="18">
                <el-row :class="[i2 == 0 ? '' : 'baar', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6"
                    ><el-tag type="success" closable @close="removeRoles(scope.row, item2.id)">{{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="18"
                    ><el-tag type="warning" closable @close="removeRoles(scope.row, item3.id)" v-for="item3 in item2.children" :key="item3.id">{{ item3.authName }}</el-tag></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色姓名" width="250"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removerolesById(scope.row)"></el-button>
            <!-- 分配权限 -->
            <el-tooltip effect="dark" content="分配角色" placement="right" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--  添加按钮 start   -->
      <el-dialog title="添加角色" :visible.sync="DialogAdd">
        <el-form label-width="80px" :model="RolesEditFrom" ref='addFormRef' :rules="RouleEditForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="RolesEditFrom.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="RolesEditFrom.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="RolesDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveAddDialog()">确 定</el-button>
        </div>
      </el-dialog>
      <!--  添加按钮 start   -->
      <!--  编辑按钮 start   -->
      <el-dialog title="编辑角色" :visible.sync="DialogEdit">
        <el-form label-width="80px" :model="RolesEditFrom" :rules="RouleEditForm">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="RolesEditFrom.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="RolesEditFrom.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="DialogEdit = false">取 消</el-button>
          <el-button type="primary" @click="saveEditDialog()">确 定</el-button>
        </div>
      </el-dialog>
      <!--  编辑按钮 start   -->

      <!-- 分配权限 start   -->
      <el-dialog title="分配权限" :visible.sync="RolesDialog" @close="clear">
        <el-tree :data="rolesListAll" show-checkbox :default-checked-keys="defaultcheckedkeys" default-expand-all node-key="id" :props="defaultProps" ref="rightsFrom"> </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="RolesDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRoules()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限 EEEEend -->
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      rolesListAll: [],
      RolesDialog: false,
      defaultcheckedkeys: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      DialogEdit: false,
      DialogAdd: false,
      RolesEditFrom: {
        roleName: '',
        roleDesc: ''
      },
      roleId: '',
      RouleEditForm: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '角色名称的长度在2~10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '角色描述的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    getroule() {
      //获取角色
      this.$http
        .get(`roles`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('获取列表失败！')
          }
          this.rolesList = result.data.data
        })
        .catch(err => {
          console.log(err)
        })
    },
    showEditDialog(scope) {
      this.DialogEdit = true
      //console.log(scope);
      this.RolesEditFrom.roleName = scope.roleName
      this.RolesEditFrom.roleDesc = scope.roleDesc
      this.roleId = scope.id
    },
    saveEditDialog() {
      this.$http
        .put(`roles/${this.roleId}`, {
          roleName: this.RolesEditFrom.roleName,
          roleDesc: this.RolesEditFrom.roleDesc
        })
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('更新失败！')
          }
          this.$message.success('更新成功')
          this.getroule()
          this.DialogEdit = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    removerolesById() {
      console.log('删除')
    },
    setRoleDialog(row) {
      //分配按钮 请求数据
      this.RolesDialog = true
      this.roleId = row.id
      this.$http
        .get(`rights/tree`)
        .then(result => {
          if (result.data.meta.status != 200) return this.$message.err('获取信息失败')
          this.rolesListAll = result.data.data
          // 递归获取三级节点的Id
          this.getcheckkey(row, this.defaultcheckedkeys)
        })
        .catch(err => {
          console.log(err)
        })
    },
    clear() {
      //清空选中的
      this.defaultcheckedkeys = []
    },
    rulesAdd() {
      this.DialogAdd = true
    },
    saveAddDialog() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.$http
          .post('roles', this.RolesEditFrom)
          .then(result => {
            if (result.data.meta.status !== 201) {
              return this.$message.error('添加失败')
            }
            this.$message.success('添加成功')
            this.DialogAdd = false
            this.RolesEditFrom = {}
            this.getroule()
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    saveRoules() {
      console.log('分配权限')
      this.RolesDialog = false
      const keys = [...this.$refs.rightsFrom.getCheckedKeys(), ...this.$refs.rightsFrom.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: idStr })
        .then(result => {
          console.log(result.data)
          if (result.data.meta.status !== 200) {
            return this.$message.error('添加失败')
          }
          this.$message.success('添加成功')
          this.getroule()
        })
        .catch(err => {
          console.log(err)
        })
    },
    getcheckkey(node, arr) {
      //递归函数
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getcheckkey(item, arr)
      })
    },
    removeRoles(roles, id) {
      //确定是否删除权限
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteRoles(roles, id)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    //删除方法
    deleteRoles(roles, id) {
      this.$http
        .delete(`roles/${roles.id}/rights/${id}`)
        .then(result => {
          if (result.data.meta.status !== 200) {
            return this.$message.error('删除失败！')
          }
          this.$message.success('删除成功')
          roles.children = result.data.data
        })
        .catch(err => {
          console.log(err)
        })
    }
  },
  mounted() {
    this.getroule()
  }
}
</script>
<style lang="less" scoped>
.rowBorder {
  border-bottom: 1px solid #ccc;
}
.bdTopBorder {
  border-top: 1px solid #ccc;
}
.baar {
  border-top: 1px solid #f00;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
